import Taro from '@tarojs/taro';
import { Canvas, View } from '@tarojs/components';
import { useEffect, useRef } from 'react';

const CircularProgress = ({
  percent = 0,
  size = 200,
  strokeWidth = 20,
  progressColor = '#1890ff',
  backgroundColor = '#e5e5e5'
}) => {
  const canvasRef = useRef<any>(null);

  const drawProgress = () => {
    Taro.nextTick(() => {
      const query = Taro.createSelectorQuery();
      query.select('#progressCanvas')
        .fields({ node: true, size: true })
        .exec((res) => {
          const canvas = res[0]?.node;
          if (!canvas) return;
          
          const ctx = canvas.getContext('2d');
          const dpr = Taro.getSystemInfoSync().pixelRatio;
          canvas.width = size * dpr;
          canvas.height = size * dpr;
          ctx.scale(dpr, dpr);
          
          const centerX = size / 2;
          const centerY = size / 2;
          const radius = (size - strokeWidth) / 2;

          // 清除画布
          ctx.clearRect(0, 0, size, size);

          // 绘制背景圆环
          ctx.beginPath();
          ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
          ctx.strokeStyle = backgroundColor;
          ctx.lineWidth = strokeWidth;
          ctx.stroke();

          // 绘制进度圆环
          ctx.beginPath();
          const startAngle = -Math.PI / 2;
          const endAngle = -Math.PI / 2 + (2 * Math.PI * (percent / 100));
          ctx.arc(centerX, centerY, radius, startAngle, endAngle);
          ctx.strokeStyle = progressColor;
          ctx.lineWidth = strokeWidth;
          ctx.lineCap = 'round';
          ctx.stroke();
        });
    });
  };

  useEffect(() => {
    drawProgress();
  }, [percent, size, strokeWidth, progressColor, backgroundColor]);

  return (
    <View className='container'>
      <Canvas
        id='progressCanvas'
        ref={canvasRef}
        type='2d'
        style={{ width: `${size}px`, height: `${size}px` }}
      />
    </View>
  );
};

export default CircularProgress;
